package com.xtu.hrms.controller;

import com.xtu.hrms.bean.User;
import com.xtu.hrms.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
public class LoginController {

//    定义后台用户业务对象
    @Autowired
    private IUserService userService;

//    @RequestMapping("/")
//    public String index() {
//        return "login";
//    }


    @GetMapping("/user/login")
    public String toLogin(){
        return "login";
    }

    @PostMapping("/user/login")
    public String login(User user, Map<String, Object> map, HttpSession session ,String password){
//        根据用户名和密码进行登录校验
        User u = userService.login(user);

        if(u==null) {
//        登录失败
            map.put("msg", "用户名不存在或密码错误！");
            return "login";
        }
       /*  else if (user.getUsername()!="admin"){
            return "emp/list1";
        } */
        else {
//            登录成功，防止表单重复提交，可以重定向到主页
            session.setAttribute("loginUser",user.getUsername());
            return "redirect:/main.html";
        }

    }

    @GetMapping("/user/register")
    public String toRegister(){
        return "register";
    }


    @PostMapping("/user/register")
    public String register(String username,String password){
        userService.addUser(new User(username,password));
        return "success";

    }


    @RequestMapping(value = "/user/logout")
    public String logout(){
        return "login";
    }



    @GetMapping("/admin/login")
    public String toAdmin(){
        return "adminLogin";
    }



    @PostMapping ("/admin/login")
    public String adminLogin(User user, Map<String, Object> map, HttpSession session ,String password){
//        根据用户名和密码进行登录校验
        User u = userService.login(user);

        if(u==null) {
//        登录失败
            map.put("msg", "用户名不存在或密码错误！");
            return "adminLogin";
        }

        else {
//            登录成功，防止表单重复提交，可以重定向到主页
            session.setAttribute("loginUser",user.getUsername());
            return "redirect:/main1.html";
        }

    }


}
